package com.zzstm.educenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzstm.commonUtils.*;
import com.zzstm.educenter.entity.UcenterMember;
import com.zzstm.educenter.entity.vo.RegisterVO;
import com.zzstm.educenter.service.UcenterMemberService;
import com.zzstm.servicebase.ex.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-11-12
 */
@RestController
@RequestMapping("/educenter/member")
@CrossOrigin
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService memberService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //登录
    @PostMapping("/login")
    public R login(@RequestBody UcenterMember member){
//        String token = memberService.login(member);
        String mobile = member.getMobile();
        String pwd = member.getPassword();
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",member.getMobile());
        UcenterMember mobileMember = memberService.getOne(queryWrapper);
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(pwd)){
            return R.error().message("请填写完整信息");
        }
        if (mobileMember == null){
            return R.error().message("用户未注册");
        }
        if (!MD5.encrypt(pwd).equals(mobileMember.getPassword())){
            return R.error().message("密码错误");
        }
        if (mobileMember.getIsDisabled()){
            return R.error().message("账号被禁用");
        }
        //登录成功，生成token
        String token = JwtUtils.getJwtToken(mobileMember.getId(),mobileMember.getNickname());

        return R.ok().data("token",token);
    }

    @PostMapping("/register")
    public R register(@RequestBody RegisterVO registerVO){
        String nickname = registerVO.getNickname();
        //将昵称编码
        nickname = Base64EnCodeAndDecode.encode(nickname);
        registerVO.setNickname(nickname);
        String mobile = registerVO.getMobile();
        String password = registerVO.getPassword();
        String code = registerVO.getCode();
        if (StringUtils.isEmpty(nickname) || StringUtils.isEmpty(mobile)
                || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)){
            return R.error().data("msg","数据不能为空");
        }
        String redisCode = redisTemplate.opsForValue().get(mobile);
        if (redisCode == null){
            return R.error().data("msg","验证码已过期");
        }
        if (!redisCode.equals(code)){
            return R.error().data("msg","验证码错误");
        }
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        UcenterMember member = memberService.getOne(wrapper);
        if (member != null){
            return R.error().data("msg","用户已存在");
        }
        //清空验证码
        redisTemplate.delete(mobile);
        memberService.register(registerVO);
        return R.ok();
    }

    //根据token获取用户信息
    @GetMapping(("/getUserInfo"))
    public R getUserInfo(HttpServletRequest request) throws UnsupportedEncodingException {
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMember user = memberService.getById(userId);
//        if (user.getOpenid() != null) {
            //将昵称解码
//            Base64.Decoder decoder = Base64.getDecoder();
//            System.err.println("****83行" + user.getNickname());
//            String nickname = user.getNickname();
//            System.err.println("---" + user);
//            byte[] decode = decoder.decode(nickname);
//            nickname = new String(decode, StandardCharsets.UTF_8);
//            user.setNickname(nickname);
//            System.err.println(nickname + "===");
//            System.err.println(user + "***");
//            System.err.println("===");
        String nickName = Base64EnCodeAndDecode.decode(user.getNickname());
        user.setNickname(nickName);
//        }
        return R.ok().data("user",user);
    }

    //根据用户id获取用户信息
    @GetMapping("/getUserInfoById/{id}")
    public UcenterMemberCommon getUserInfoById(@PathVariable String id){
        UcenterMember member = memberService.getById(id);
        UcenterMemberCommon ucenterMemberCommon = new UcenterMemberCommon();
        BeanUtils.copyProperties(member,ucenterMemberCommon);
        return ucenterMemberCommon;
    }

    //查询某天注册人数
    @GetMapping("/countRegister/{day}")
    public R countRegister(@PathVariable String day){
        Integer count = memberService.countRegister(day);
        return R.ok().data("count",count);
    }

}

